/**
 * PDF生成工具函数
 */

/**
 * 动态加载脚本
 * @param {string} url 脚本URL
 * @returns {Promise<void>}
 */
const loadScript = (url) => {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = url;
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
};

/**
 * 确保脚本已加载
 * @returns {Promise<void>}
 */
const ensureScriptsLoaded = async () => {
  if (!window.html2canvas || !window.jspdf) {
    await Promise.all([
      loadScript('https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js'),
      loadScript('https://cdn.jsdelivr.net/npm/jspdf@2.5.1/dist/jspdf.umd.min.js')
    ]);
  }
};

/**
 * 生成简历PDF
 * @param {HTMLElement} element 要转换为PDF的DOM元素
 * @param {string} filename 文件名
 * @returns {Promise<void>}
 */
export const generateResumePDF = async (element, filename = '简历') => {
  try {
    // 确保脚本已加载
    await ensureScriptsLoaded();
    
    // 使用全局变量
    const html2canvasLib = window.html2canvas;
    const { jsPDF } = window.jspdf;
    
    // 创建canvas
    const canvas = await html2canvasLib(element, {
      scale: 2, // 提高清晰度
      useCORS: true, // 允许加载跨域图片
      logging: false,
      backgroundColor: '#ffffff' // 设置背景色为白色
    });
    
    // 创建PDF文档（A4尺寸）
    const pdf = new jsPDF('p', 'mm', 'a4');
    
    // 计算宽高比
    const imgWidth = 210; // A4宽度(mm)
    const pageHeight = 297; // A4高度(mm)
    const imgHeight = (canvas.height * imgWidth) / canvas.width;
    
    // 检查是否需要调整比例以适应一页
    let scale = 1;
    if (imgHeight > pageHeight) {
      scale = pageHeight / imgHeight;
      console.log('调整缩放比例为:', scale);
    }
    
    // 计算调整后的尺寸
    const adjustedWidth = imgWidth * scale;
    const adjustedHeight = imgHeight * scale;
    
    // 计算居中位置
    const xOffset = (imgWidth - adjustedWidth) / 2;
    const yOffset = (pageHeight - adjustedHeight) / 2;
    
    // 将canvas添加到PDF
    const imgData = canvas.toDataURL('image/png');
    pdf.addImage(imgData, 'PNG', xOffset, yOffset, adjustedWidth, adjustedHeight);
    
    // 保存PDF
    pdf.save(`${filename}.pdf`);
    
    return pdf; // 返回PDF对象，以便后续可能的操作
  } catch (error) {
    console.error('生成PDF时发生错误:', error);
    throw error;
  }
};

/**
 * 打印简历
 * @param {HTMLElement} element 要打印的DOM元素
 * @returns {Promise<void>}
 */
export const printResume = async (element) => {
  try {
    const pdf = await generateResumePDF(element, 'temp_print');
    pdf.autoPrint();
    window.open(pdf.output('bloburl'), '_blank');
  } catch (error) {
    console.error('打印简历时发生错误:', error);
    throw error;
  }
}; 